package com.blockmeta.bbs.businesslibrary.widget.chartview.Layer;

import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.RectF;
import android.text.TextUtils;


import com.blockmeta.bbs.baselibrary.base.app.BaseApp;
import com.blockmeta.bbs.baselibrary.utils.DimentionsUtil;
import com.blockmeta.bbs.baselibrary.utils.FormatUtil;
import com.blockmeta.bbs.businesslibrary.R;
import com.blockmeta.bbs.businesslibrary.websocket.Symbol;
import com.blockmeta.bbs.businesslibrary.widget.chartview.Axis.Coordinate;
import com.blockmeta.bbs.businesslibrary.widget.chartview.Axis.MoveCoordinate;
import com.blockmeta.bbs.businesslibrary.widget.chartview.CandleData;
import com.blockmeta.bbs.businesslibrary.widget.chartview.ChartData;
import com.blockmeta.bbs.businesslibrary.widget.chartview.Tools.KDJIndicator;
import com.blockmeta.bbs.businesslibrary.widget.chartview.Tools.KdjData;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


class KDJLayer extends BasicLayer
{
	protected final double m_dbNone = Double.MIN_VALUE;
	private int beginIdx;//用于存储第一个指标第一个值的位置
	private int mPeriod = 9,m1 = 3,m2 = 3;
	private String m_k = "",m_d = "",m_j = "";
	private String m_lastk = "",m_lastd = "",m_lastj = "";
	private int m_color1 = 0xFF4A86EA,m_color2 = 0xFFFF72A5,m_color3 = 0xFFFFA200,m_color0 = 0xFF808080;

	public KDJLayer()
	{
		super();
	}

	@Override
	public Coordinate createCoordinate()
	{
		return new MoveCoordinate();
	}

	@Override
	public boolean onCalculateData()
	{
		ArrayList<String> params = new ArrayList<>(Arrays.asList("9", "3", "3"));//FDTStorage.getInstance().getArray(SaveKey.CHART_INDICATOR_KDJ + "param", SaveKey.CHART_INDICATOR_PARAM);
		if (params != null)
		{
			mPeriod = !TextUtils.isEmpty(params.get(0)) ? Integer.parseInt(params.get(0)) : 5;
			m1 = !TextUtils.isEmpty(params.get(1)) ? Integer.parseInt(params.get(1)) : 3;
			m2 = !TextUtils.isEmpty(params.get(2)) ? Integer.parseInt(params.get(2)) : 3;
		}


//		testMacd();
		//获得数据源
		List<CandleData> tDataList = m_callback.getCandleDataList();
		int tListSize = tDataList.size();

		beginIdx = mPeriod;
		KDJIndicator kdjIndicator = new KDJIndicator();
		List<KdjData> kdjDatas = kdjIndicator.computeKDJ(tDataList,mPeriod,m1,m2);

		CandleData candle;
		KdjData kdj;
		for (int i = 0; i < tListSize; i++)//修改数据源
		{
			candle = tDataList.get(i);
			kdj = kdjDatas.get(i);
			if(candle != null && kdj != null)
			{
				candle.setDbOpen(kdj.getK());
				candle.setDbClose( kdj.getD());
				candle.setDbHigh(kdj.getJ());
			}
		}

		return true;
	}




	protected int getDataStartIndex()
	{
		return getMoveStartIndex();
	}

	/**
	 * 获取数据的移动位置
	 * @return
	 */
	protected int getMoveStartIndex()
	{
		Coordinate tCoordinate = m_callback.getCoordinate();
		if(tCoordinate != null)
		{
			return tCoordinate.getStartIndex();
		}
		return 0;
	}

	@Override
	public Layer.ChartTypeEnum getLayerTypeEnum()
	{
		return Layer.ChartTypeEnum.KDJ;
	}

	public List<CandleData> convertDate(List<CandleData> pList)
	{
		return pList;
	}

	@Override
	public void drawYesterClose(Canvas pCanvas, Paint pPaint)
	{
	}

	@Override
	public void onDrawLayer(Canvas pCanvas, Paint pPaint, Point pPoint)
	{
		//获取坐标系
		Coordinate tCoordinate = m_callback.getCoordinate();
		//转化处理数据
		List<CandleData> tDataList = convertDate(m_callback.getCandleDataList());

		//定义初始化文本
		String tCloseText = null;
		String tOpenText = null;
		String tHighText = null;
		String tLowText = null;
		String tTimeText = null;
		String tValueText = null;
		String tVolumnText = null;
		int tXPoint = pPoint.x;


		if (tDataList != null && tDataList.size() > 0)
		{
			int tListSize = tDataList.size();
//			int tStartIndex = tCoordinate.getStartIndex();

			float tXFirstPosition = tCoordinate.getXFirstPosition();
			float tXInterval = tCoordinate.getXInterval();
			float tYFirstposition = tCoordinate.getYFirstPosition();
			// float tYFirstposition = tCoordinate.getYFirstPosition();
			float tYMaxValue = tCoordinate.getMaxValue();
			float tYMinValue = tCoordinate.getMinValue();
			float tYValueDist = tYMaxValue - tYMinValue;
			float tYValueLength = tCoordinate.getValueHeight();
			// float tYValueLength = tCoordinate.getYInterval() *
			// tCoordinate.getYIntervalCount();

			float tCurrentYPosition = 0.f;
			float tTempYPosition = 0.f;
			float tCurrentXPosition = 0.f;
			float tTempXPosition = 0.f;

			float tCurrentYPosition1 = 0.f;
			float tTempYPosition1 = 0.f;
			float tCurrentXPosition1 = 0.f;
			float tTempXPosition1 = 0.f;

			float tCurrentYPosition2 = 0.f;
			float tTempYPosition2 = 0.f;
			float tCurrentXPosition2 = 0.f;
			float tTempXPosition2 = 0.f;

			int m_bDigit = m_callback.getDigit();

			Symbol symbol = m_callback.getCoordinate().tSymBol;
			float tLineWidth = 2.f;
			pPaint.setAntiAlias(true);

			boolean tStartDraw = false;

			int tDotColor = BaseApp.getApp().getResources().getColor(R.color.sys_even);
			int tCulOffset = 1;

			int dataStart = getDataStartIndex(); //tStartIndex + getStartIndex();

			int moveStart = getMoveStartIndex();
			int displayCount = m_callback.getDisplayCount();//获取当前要显示的个数
			int minCount = Math.min(moveStart+displayCount,tListSize);//不能超出数据集宽度
//			FDTLogUtils.d("tingchart",getLayerTypeEnum()+"layer from draw tStartIndex"+dataStart+" to mincount"+minCount);
			if(dataStart > tListSize)//如果数据量不足以算出一个值
			{
				return;
			}
			CandleData candle = null;
			for (int i = dataStart; i < minCount; i++)
			{
				//如果收盘价为空就跳过
				candle = tDataList.get(i);
				if (candle.getDbClose() == m_dbNone || candle.getDbHigh() == m_dbNone || candle.getDbOpen() == m_dbNone)
				{
					continue;
				}

				pPaint.setColor(m_callback.getColor());
				pPaint.setStrokeWidth(tLineWidth);

				float td = (float) candle.getDbClose();
				float tk = (float) candle.getDbOpen();
				float tj = (float) candle.getDbHigh();

				tTempXPosition = tCurrentXPosition;
				tCurrentXPosition = tXFirstPosition + tXInterval * (i - moveStart);
				tTempYPosition = tCurrentYPosition;
				tCurrentYPosition = tYFirstposition - ((tk - tYMinValue) * tYValueLength / tYValueDist);

				tTempXPosition1 = tCurrentXPosition1;
				tCurrentXPosition1 = tXFirstPosition + tXInterval * (i - moveStart);
				tTempYPosition1 = tCurrentYPosition1;
				tCurrentYPosition1 = tYFirstposition - ((td - tYMinValue) * tYValueLength / tYValueDist);

				tTempXPosition2 = tCurrentXPosition2;
				tCurrentXPosition2 = tXFirstPosition + tXInterval * (i - moveStart);
				tTempYPosition2 = tCurrentYPosition2;
				tCurrentYPosition2 = tYFirstposition - ((tj - tYMinValue) * tYValueLength / tYValueDist);

				if (((tCurrentXPosition - tXInterval / 2) <= pPoint.x && pPoint.x < (tCurrentXPosition + tXInterval / 2))|| ((i == minCount - 1) && pPoint.x > tCurrentXPosition + tXInterval / 2))
				{
					float tValueaa = (tYFirstposition - pPoint.y) * tYValueDist / tYValueLength + tYMinValue;
					m_k = FormatUtil.getFormatString(tk, m_bDigit + 1);
					m_d = FormatUtil.getFormatString(td, m_bDigit + 1);
					m_j = FormatUtil.getFormatString(tj, m_bDigit + 1);
					ChartData.ChartPeroid tChartType = m_callback.getChartType();
					tValueText = FormatUtil.getFormatString(tValueaa, m_bDigit);
					tTimeText = getDisplayX(tChartType, tDataList.get(i));

					tXPoint = (int) tCurrentXPosition;
				}

				if (tStartDraw)
				{
					RectF tRectF = tCoordinate.getLayerRectF();
					pPaint.setColor(m_color1);
					drawLine(pCanvas, pPaint, tCurrentYPosition, tTempYPosition, tCurrentXPosition, tTempXPosition, tCulOffset, tRectF);
					pPaint.setColor(m_color2);
					drawLine(pCanvas, pPaint, tCurrentYPosition1, tTempYPosition1, tCurrentXPosition1, tTempXPosition1, tCulOffset, tRectF);
					pPaint.setColor(m_color3);
					drawLine(pCanvas, pPaint, tCurrentYPosition2, tTempYPosition2, tCurrentXPosition2, tTempXPosition2, tCulOffset, tRectF);
				}
				else
				{
					tStartDraw = true;
				}

				if (tDataList.get(i).m_bDrawDot)
				{
					pPaint.setColor(tDotColor);
					pCanvas.drawCircle(tCurrentXPosition, tCurrentYPosition, tLineWidth * 2, pPaint);
				}

				if(i == minCount - 1)
				{
					if(candle != null)
					{
						m_lastk = FormatUtil.getFormatString(candle.getDbOpen(), m_bDigit + 1);
						m_lastj = FormatUtil.getFormatString(candle.getDbHigh(), m_bDigit + 1);
						m_lastd = FormatUtil.getFormatString(candle.getDbClose(), m_bDigit + 1);
					}
				}
			}
		}

		setCrossData(pCanvas, pPaint, tTimeText, tValueText, new Point(tXPoint, pPoint.y));

	}

	private void drawLine(Canvas pCanvas, Paint pPaint, float tCurrentYPosition, float tTempYPosition, float tCurrentXPosition, float tTempXPosition, int tCulOffset, RectF tRectF)
	{

		pCanvas.drawLine(tTempXPosition, tTempYPosition, tCurrentXPosition, tCurrentYPosition, pPaint);
	}

	private String getDigitString(String value, int digit)
	{
		if (! TextUtils.isEmpty(value))
		{
			try
			{
				value = FormatUtil.getFormatString(Double.parseDouble(value), digit);
			}
			catch (Exception e)
			{
			}
		}
		else
		{
			value = "";
		}

		return value;
	}

	private float getScale(float start, float end, float middle)
	{
		return (start - middle) / (start - end);
	}

	private void resetIndicatorData()
	{
		m_k = "";
		m_d = "";
		m_j = "";
		m_lastk = "";
		m_lastd = "";
		m_lastj = "";
	}
	/**
	 * draw layer left－top text
	 * 获取指标值进行显示
	 * @param pCanvas
	 * @param pPaint
	 */
	@Override
	public void drawFloatIndicatorText(boolean longtouch,Canvas pCanvas, Paint pPaint)
	{

		if (!m_callback.needFloatIndicatorText())
		{
			return;
		}

		List<CandleData> tDataList = m_callback.getCandleDataList();
		if(tDataList == null || tDataList.size() == 0)
		{
			resetIndicatorData();
		}

		Coordinate tCoordinate = m_callback.getCoordinate();
		RectF tLayerRect = tCoordinate.getLayerRectF();

		float tLeftPadding = DimentionsUtil.dp2px(0);
		float tButtomPadding = DimentionsUtil.dp2px(1);
		float tWordPadding = DimentionsUtil.dp2px(10);

		String indicatorText0 = String.format("KDJ(%s,%s,%s)", mPeriod, m1, m2);
		String indicatorText1;
		String indicatorText2;
		String indicatorText3;
		if (longtouch)
		{
			indicatorText1 = "K:" + m_k;
			indicatorText2 = "D:" + m_d;
			indicatorText3 = "J:" + m_j;
		}
		else
		{
			indicatorText1 = "K:" + m_lastk;
			indicatorText2 = "D:" + m_lastd;
			indicatorText3 = "J:" + m_lastj;
		}
		pPaint.setAntiAlias(true);
		float textSize = DimentionsUtil.dp2px(10);
		pPaint.setTextSize(textSize);
		float tTxtWidth0 = pPaint.measureText(indicatorText0);
		float tTxtWidth1 = pPaint.measureText(indicatorText1);
		float tTxtWidth2 = pPaint.measureText(indicatorText2);

		pPaint.setColor(m_color0);
		pCanvas.drawText(indicatorText0, tLayerRect.left + tLeftPadding, tLayerRect.top + tButtomPadding + textSize, pPaint);
		pPaint.setColor(m_color1);
		pCanvas.drawText(indicatorText1, tLayerRect.left + tLeftPadding + tWordPadding + tTxtWidth0, tLayerRect.top + tButtomPadding + textSize, pPaint);
		pPaint.setColor(m_color2);
		pCanvas.drawText(indicatorText2, tLayerRect.left + tLeftPadding + tWordPadding * 2 + tTxtWidth0 + tTxtWidth1, tLayerRect.top + tButtomPadding + textSize, pPaint);
		pPaint.setColor(m_color3);
		pCanvas.drawText(indicatorText3, tLayerRect.left + tLeftPadding + tWordPadding * 3 + tTxtWidth0 + tTxtWidth1 + tTxtWidth2, tLayerRect.top + tButtomPadding + textSize, pPaint);

	}
}
